<?php

/*
 * Edit by shengxin
 * Click nbfs://nbhost/SystemFileSystem/Templates/Scripting/PHPClass.php to edit this template
 */

namespace api\mall\controller;

use cmf\controller\BaseController;
use app\user\model\UserModel;
/**
 * Description of LoginController
 *
 * @author PC
 */
class LoginController extends BaseController{
    
    protected function getResponseType(): string {
        return 'json';
    }
    public function login(){
        $data = $this->request->post();
        if(empty($data['username'])){
            $this->error('username is empty');
        }
        $username = $data['username'];
        do{
            $userModel = new UserModel();
            $user = $userModel->where('mobile', $username)->find();
            if(isset($data['code'])){
                $code = $data['code'];
                $result = cmf_check_verification_code($username, $code);
                if($result !== true){
                    break;
                }
            }else if(isset ($data['password'])){
                $result = '账号或密码错误';
                if(empty($user)){
                    break;
                }
                $passwordInDb = $user['user_pass'];
                if(cmf_compare_password($data['password'], $passwordInDb) !== true){
                    break;
                }
            }            
            
            //清理验证码
//            cmf_clear_verification_code($username);
            
            
            $uid = 0;
            if(empty($user)){
                $user = [
                    'user_type'=>2,
                    'sex'=>0,
                    'create_time'=> time(),
                    'user_status'=>1,
                    'user_nickname'=>'用户'.(time()%100000),
                    'last_login_ip'=>$this->request->ip(),
                    'mobile'=>$username,
                    'user_login'=>$username
                ];
                $uid = $userModel->insertGetId($user);
            }else{
                $uid = $user['id'];
                unset($user['user_pass']);
            }

            //拉黑判断。
            if ($user['user_status'] == 0) {
                $result = '你已经限制登录，暂时无法登录';
                break;
            }
                    
            $data = [
                'last_login_time' => time(),
                'last_login_ip'   => get_client_ip(0, true),
            ];
            $userModel->where('id', $uid)->update($data);
            $token = cmf_generate_user_token($uid, 'web');
            $hookParam = [
                'user'                    => $user,
                'compare_password_result' => false
            ];
            hook_one("user_login_start", $hookParam);
            $user['token'] = $token;
            $this->success('ok','',$user);
        }while(false);
        $this->error($result);
    }
}
